package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";

    private static final String ADD_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.addStock";
    
    private SqlSession sqlSession;
    @Transactional
    @Override
    public void deductStock(Map<Long, Integer> cartMap) {

        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {

            // 准备参数
            Map<String,Object> param = new HashMap<>();
            param.put("id",entry.getKey());
            param.put("num",entry.getValue());
            // 编译statement，namespace.statementId
            sqlSession.update(DEDUCT_STOCK_STATEMENT,param);
            // 刷新
            sqlSession.flushStatements();
        }
    }

    @Override
    @Transactional
    public void addStock(Map<Long, Integer> cartMap) {

        executeBatch(sqlSession1 -> {

            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {

                Map<String,Object> param = new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
                sqlSession.update(ADD_STOCK_STATEMENT,param);
                sqlSession.flushStatements();
            }
        });
    }
}
